package com.jxmdkt.controller;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;

import org.eclipse.jetty.util.ajax.JSONPojoConvertor.Setter;

import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.jxmdkt.common.CheckLoginInterceptor;
import com.jxmdkt.common.ExcelUtils;
import com.jxmdkt.common.MD5;
import com.jxmdkt.model.AdminModel;
import com.jxmdkt.model.Constants;
import com.jxmdkt.model.UinfoModel;

public class AdminController extends Controller{
	public static final int pageSize=20;
	
	public void index(){
		renderJsp("/admin/indexMain.jsp");
	}
	public void menu(){
		
		AdminModel model=getSessionAttr("loginedadmin");
		setAttr("adminid", model.getStr("id"));
		setAttr("name", model.getStr("name"));
		setAttr("permission", model.getStr("permission"));
		render("/admin/menuTree.jsp");
	}
	
	public void deliver(){
		String[] cardnos=getPara("cardnos").split(";");
		UinfoModel.dao.deliver(cardnos);
		forwardAction("/admin/query");
	}
	
	public  void deliverexcel(){ 
		final UploadFile file =getFile("deliverfile");
		try {

			final List<UinfoModel> models=ExcelUtils.readDeliverExcel(file.getFile());
			Db.tx(new IAtom() {
				boolean b =true;
				@Override
				public boolean run() throws SQLException {
					for(UinfoModel model:models){
						b=model.update();
					}
					file.getFile().delete();
					return b;
				}
			});
			setAttr("deliverrst", "数据导入成功！");
		} catch ( Exception e) {
			e.printStackTrace();
			setAttr("deliverrst", "数据导入失败，请重新导入！");
		}
		forwardAction("/admin/doimport");
	}
	public void query(){
		
		AdminModel model=getSessionAttr("loginedadmin");
		setAttr("permission", model.getStr("permission"));
		String querycondition=getPara("querycondition","0");
		String deliveredcondition=getPara("deliveredcondition","0");
		String starttime=getPara("starttime");
		String endtime=getPara("endtime");
		int pageNumber=getParaToInt("pageNumber",1);
		
		Page< UinfoModel> page=null;

		page=UinfoModel.dao.query(pageNumber, pageSize, starttime, endtime, querycondition,deliveredcondition);
		setAttr("page",page);
		keepPara("starttime","endtime","querycondition","deliveredcondition");
		render("/admin/cards.jsp");

	}
	
	public void exportAll(){
		ServletOutputStream out = null;
		try{
		  getResponse().setContentType("text/csv");
		  String disposition = "attachment; fileName=data_"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".csv";
		  getResponse().setHeader("Content-Disposition", disposition);
		  out = getResponse().getOutputStream();
			String querycondition=getPara("querycondition","0");
			String deliveredcondition=getPara("deliveredcondition","0");
			String starttime=getPara("starttime");
			String endtime=getPara("endtime");
			int pagecount=getParaToInt("pagecount");
		  List<UinfoModel> list=UinfoModel.dao.query(1, pagecount, starttime, endtime, querycondition,deliveredcondition).getList();
	//	  list=new ArrayList<UinfoModel>();
		  byte[] blobData=ExcelUtils.createExcel(list);
		  out.write(blobData);
		  out.flush();
		  out.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		query();
	}
	public void showcards(){
		Page<UinfoModel> page=UinfoModel.dao.findAll(1, pageSize);
		setAttr("page", page);
		
		AdminModel model=getSessionAttr("loginedadmin");
		setAttr("permission", model.getStr("permission"));
		setAttr("querycondition", "0");
		setAttr("deliveredcondition", "0");
		render("/admin/cards.jsp");
	}
	public void importer(){
		final UploadFile file =getFile("fileUpload");
		
		
		try {
			final List<UinfoModel> models=ExcelUtils.readExcel(file.getFile());
			Db.tx(new IAtom() {
				@Override
				public boolean run() throws SQLException {
					for(UinfoModel model:models){
						model.save();
					}
					file.getFile().delete();
					return true;
				}
			});
			setAttr("importrst", "数据导入成功！");
		} catch ( Exception e) {
			e.printStackTrace();
			setAttr("importrst", "数据导入失败，请重新导入！");
		}
		forwardAction("/admin/doimport");
	}
	public void doimport(){
		render("/admin/import.jsp");
	}
	public void changepassword(){
		render("/admin/cp.jsp");
	}
	
	public void adminmanage(){
		int pagenow=(Integer) (getParaToInt("pageNumber")==null?1:getParaToInt("pageNumber"));
		System.out.println(pagenow);
		setAttr("page", AdminModel.dao.paginate(pageSize, pagenow));
		render("/admin/admins.jsp");
	}
	public void tocreateadmin(){
		render("/admin/cadmin.jsp");
	}
	public void dochangepassword(){
		AdminModel model=getSessionAttr("loginedadmin");
		String oldpassword=getPara("oldpassword");
		String newpassword=getPara("newpassword");
		String changetype=getPara("changetype");
		if(oldpassword.equals(model.getStr("password"))){
			model.set("password", newpassword);
			model.update();
			setAttr("changemessage", "密码修改成功，下次登录请使用新密码！");
		}else {
			setAttr("changemessage", "原密码错误，不能修改密码！");
		}
		if(changetype==null||changetype.equals(""))
			render("/admin/cp.jsp");
		else
			forwardAction("/relogin");
	}
	public void lunch(){
		String id=getPara("adminid");
		boolean res=AdminModel.dao.changestatus(id,Constants.ADMINSTATUS_LUNCHED);
		if(res==true){
			setAttr("hiddenmessage", "用户启用成功！");
		}else {
			setAttr("hiddenmessage", "用户启用失败，请稍后再试！");
		}
		forwardAction("/admin/adminmanage");
	}
	public void hidden(){
		String id=getPara("adminid");
		boolean res=AdminModel.dao.changestatus(id,Constants.ADMINSTATUS_HIDDEN);
		if(res==true){
			setAttr("hiddenmessage", "用户禁用成功！");
		}else {
			setAttr("hiddenmessage", "用户禁用失败，请稍后再试！");
		}
		forwardAction("/admin/adminmanage");
	}
	public void list(){
		int pagenow=getAttr("pageNumber");
		Page<AdminModel> models=AdminModel.dao.paginate(pageSize, pagenow);
	}
	
	public void createadmin(){
		String id=getPara("adminid");
		String  name=getPara("adminname");
		String permission=getPara("permission");
		AdminModel model=new AdminModel();
		model.set("id", id).set("name", name).set("permission", permission).set("status", Constants.ADMINSTATUS_LUNCHED).set("password", MD5.MD5(Constants.DEFAULT_PASSWORD));
		String string=AdminModel.dao.create(model);
		if(string==null)
			forwardAction("/admin/adminmanage");
		else{
			setAttr("createmessage", string);
			render("/admin/cadmin.jsp");
		}
	}
}
